<template>
	<div>
		<!-- AI助手按钮 -->
		<div v-if="showAssistantBtn" ref="assistantBtn" class="ai-assistant-btn" @mousedown="startDrag"
			@click="toggleDialog">
			<img style="border-radius: 8px; width: 100px;height: 100px;" src="./image.png" alt="ai">
		</div>

		<!-- AI对话框 -->
		<div v-if="showDialog" ref="dialog" class="ai-dialog" :style="dialogStyle">
			<div class="dialog-header" @mousedown="startDragDialog">
				<h3>AI助手</h3>
				<button @click="closeDialog" class="close-btn">×</button>
			</div>
			<div class="dialog-content">
				<div v-for="(message, index) in messages" :key="index" :class="['message', message.sender]">
					{{ message.text }}
				</div>
				<div v-if="isTyping" class="typing-indicator">
					<span></span>
					<span></span>
					<span></span>
				</div>
			</div>
			<div class="dialog-input">
				<input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入您的问题..." />
				<button @click="sendMessage">发送</button>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue';


import { getModelList, takeTalk } from '@/api/ai/getAi'
// 定义api接口, 从api获取ollama  --- 获取模型的方法
const getAiOne = async() => {
	let abc =  await getModelList()
	console.log(abc)
	Message.warning('执行了ai的模型获取接口')
}

// 定义api接口, 从api获取ollama  --- 获取模型的方法
const takeTalkOne = async(message:string) => {
	let abc:any =  await takeTalk({
  model: "gemma3:1b",  // 模型名称
  prompt: message, // 输入的提示词
  stream: false,          // 是否启用流式响应（默认 false）
  options: {              // 可选参数
    temperature: 0.7,     // 温度参数
    max_tokens: 100       // 最大 token 数
}
	})
	console.log(abc?.response,'响应数据')
	// Message.warning('执行了ai的模型获取接口')
	return abc
}

// 添加新的api逻辑
import { askAI } from '@/api/ai'; // 导入AI API
import { Message } from '@arco-design/web-vue';
// 修改 sendMessage 方法以使用真实API
const sendMessage = async () => {
	const message = userInput.value.trim();
	if (!message || isTyping.value) return;

	addMessage(message, 'user');
	userInput.value = '';
	isTyping.value = true;

	try {
		// 调用真实的AI API
		const response:any = await takeTalkOne(message);
		addMessage(response?.response, 'ai');
		console.log(response,'打印返回数据')
	} catch (error) {
		console.error('获取AI响应失败:', error);
		addMessage('抱歉，我暂时无法响应您的请求，请稍后再试。', 'ai');
	} finally {
		isTyping.value = false;
	}
};
// 到此结束 下面代码都是对的




interface Message {
	text: string;
	sender: 'user' | 'ai';
}

// 组件状态
const assistantBtn = ref<HTMLElement | null>(null);
const dialog = ref<HTMLElement | null>(null);
const showAssistantBtn = ref(true); // 控制助手按钮显示
const showDialog = ref(false);
const isDragging = ref(false);
const isDialogDragging = ref(false);
const startX = ref(0);
const startY = ref(0);
const startDialogX = ref(0);
const startDialogY = ref(0);
const userInput = ref('');
const messages = ref<Message[]>([]);
const isTyping = ref(false);
const maxZIndex = ref(1000);

// AI助手按钮的位置状态
const assistantPosition = ref({
	x: window.innerWidth / 2 - 30, // 初始位置在屏幕中心
	y: window.innerHeight / 2 - 30
});

// 对话框的位置状态
const dialogPosition = ref({
	x: window.innerWidth / 2 - 175, // 350px宽度的一半
	y: window.innerHeight / 2 - 225  // 450px高度的一半
});

// 计算对话框样式
const dialogStyle = computed(() => {
	return {
		position: 'fixed',
		left: `${dialogPosition.value.x}px`,
		top: `${dialogPosition.value.y}px`,
		width: '350px',
		height: '450px',
		background: 'white',
		'border-radius': '12px',
		'box-shadow': '0 10px 30px rgba(0, 0, 0, 0.2)',
		zIndex: maxZIndex.value + 1,
		display: 'flex',
		'flex-direction': 'column',
		overflow: 'hidden'
	};
});

// 初始化欢迎消息
onMounted(() => {
	addMessage('您好！我是AI助手，请问有什么可以帮您？', 'ai');
	updateMaxZIndex();

	// 初始化按钮位置
	if (assistantBtn.value) {
		assistantBtn.value.style.left = assistantPosition.value.x + 'px';
		assistantBtn.value.style.top = assistantPosition.value.y + 'px';
	}
});

// 更新最大z-index
const updateMaxZIndex = () => {
	const elements = document.querySelectorAll('*');
	let currentMax = 0;

	elements.forEach(el => {
		const zIndex = parseInt(getComputedStyle(el).zIndex);
		if (!isNaN(zIndex) && zIndex > currentMax) {
			currentMax = zIndex;
		}
	});

	maxZIndex.value = currentMax + 1;
};

// 开始拖动按钮
const startDrag = (e: MouseEvent) => {
	isDragging.value = true;
	// 正确计算鼠标相对于按钮的位置
	if (assistantBtn.value) {
		const rect = assistantBtn.value.getBoundingClientRect();
		startX.value = e.clientX - rect.left;
		startY.value = e.clientY - rect.top;
	}
	document.addEventListener('mousemove', dragBtn);
	document.addEventListener('mouseup', stopDragBtn);
	updateMaxZIndex();
	if (assistantBtn.value) {
		assistantBtn.value.style.zIndex = maxZIndex.value.toString();
	}
	e.preventDefault(); // 防止可能的冲突
	e.stopPropagation();
};

// 拖动按钮
const dragBtn = (e: MouseEvent) => {
	if (!isDragging.value || !assistantBtn.value) return;

	// 正确计算按钮位置
	let left = e.clientX - startX.value;
	let top = e.clientY - startY.value;

	// 限制在视窗内
	left = Math.max(0, Math.min(left, window.innerWidth - assistantBtn.value.offsetWidth));
	top = Math.max(0, Math.min(top, window.innerHeight - assistantBtn.value.offsetHeight));

	// 更新按钮位置
	assistantBtn.value.style.left = left + 'px';
	assistantBtn.value.style.top = top + 'px';

	// 保存当前位置
	assistantPosition.value = {
		x: left,
		y: top
	};
};

// 停止拖动按钮
const stopDragBtn = () => {
	isDragging.value = false;
	document.removeEventListener('mousemove', dragBtn);
	document.removeEventListener('mouseup', stopDragBtn);
};

// 开始拖动对话框
const startDragDialog = (e: MouseEvent) => {
	if (!dialog.value) return;

	isDialogDragging.value = true;
	// 正确计算鼠标相对于对话框的位置
	const rect = dialog.value.getBoundingClientRect();
	startDialogX.value = e.clientX - rect.left;
	startDialogY.value = e.clientY - rect.top;
	document.addEventListener('mousemove', dragDialog);
	document.addEventListener('mouseup', stopDragDialog);
	updateMaxZIndex();
	if (dialog.value) {
		dialog.value.style.zIndex = maxZIndex.value.toString();
	}
};

// 拖动对话框
const dragDialog = (e: MouseEvent) => {
	if (!isDialogDragging.value || !dialog.value) return;

	// 正确计算对话框位置
	let left = e.clientX - startDialogX.value;
	let top = e.clientY - startDialogY.value;

	// 限制在视窗内
	left = Math.max(0, Math.min(left, window.innerWidth - dialog.value.offsetWidth));
	top = Math.max(0, Math.min(top, window.innerHeight - dialog.value.offsetHeight));

	dialog.value.style.left = left + 'px';
	dialog.value.style.top = top + 'px';

	// 更新对话框位置状态
	dialogPosition.value = {
		x: left,
		y: top
	};

	// 注意：不更新assistantPosition，保持助手位置独立
};

// 停止拖动对话框
const stopDragDialog = () => {
	isDialogDragging.value = false;
	document.removeEventListener('mousemove', dragDialog);
	document.removeEventListener('mouseup', stopDragDialog);
};

// 切换对话框
const toggleDialog = (e: MouseEvent) => {
	// 防止拖动时触发点击事件
	if (isDragging.value) return;

	e.stopPropagation(); // 阻止事件冒泡

	// 设置对话框位置为助手位置
	dialogPosition.value = { ...assistantPosition.value };

	// 点击按钮后隐藏按钮并显示对话框
	showAssistantBtn.value = false;
	showDialog.value = true;

	if (showDialog.value && dialog.value) {
		updateMaxZIndex();
		dialog.value.style.zIndex = maxZIndex.value.toString();
		nextTick(() => {
			if (dialog.value) {
				dialog.value.scrollTop = dialog.value.scrollHeight;
			}
		});
	}
};

// 关闭对话框
const closeDialog = () => {
	showDialog.value = false;
	// 对话框关闭后重新显示按钮
	showAssistantBtn.value = true;

	// 确保按钮位置正确显示
	nextTick(() => {
		if (assistantBtn.value && showAssistantBtn.value) {
			assistantBtn.value.style.left = assistantPosition.value.x + 'px';
			assistantBtn.value.style.top = assistantPosition.value.y + 'px';
		}
	});
};

// 添加消息
const addMessage = (text: string, sender: 'user' | 'ai') => {
	messages.value.push({
		text,
		sender
	});
	nextTick(() => {
		const content = document.querySelector('.dialog-content');
		if (content) {
			content.scrollTop = content.scrollHeight;
		}
	});
};

// // 发送消息
// const sendMessage = async () => {
// 	const message = userInput.value.trim();
// 	if (!message || isTyping.value) return;

// 	addMessage(message, 'user');
// 	userInput.value = '';
// 	isTyping.value = true;

// 	try {
// 		// 模拟AI响应
// 		await new Promise(resolve => setTimeout(resolve, 800 + Math.random() * 700));

// 		const response = getAIResponse(message);
// 		addMessage(response, 'ai');
// 	} catch (error) {
// 		console.error('获取AI响应失败:', error);
// 		addMessage('抱歉，我暂时无法响应您的请求，请稍后再试。', 'ai');
// 	} finally {
// 		isTyping.value = false;
// 	}
// };

// 简单的AI响应逻辑
const getAIResponse = (message: string): string => {
	const lowerMessage = message.toLowerCase();

	if (lowerMessage.includes('你好') || lowerMessage.includes('hello')) {
		return '您好！很高兴为您服务。请问有什么可以帮您？';
	} else if (lowerMessage.includes('名字') || lowerMessage.includes('谁')) {
		return '我是一个AI助手，专门设计来回答您的问题和提供帮助。';
	} else if (lowerMessage.includes('时间')) {
		return '当前时间是：' + new Date().toLocaleTimeString();
	} else if (lowerMessage.includes('天气')) {
		return '抱歉，我目前无法获取实时天气信息。您可以尝试使用专业的天气应用或网站。';
	} else {
		return '感谢您的消息。我会尽力为您提供帮助，如果您需要更专业的协助，请告诉我更多细节。';
	}
};

// 重写api逻辑
const ddd = () => {

}



// 清理事件监听器
onUnmounted(() => {
	document.removeEventListener('mousemove', dragBtn);
	document.removeEventListener('mouseup', stopDragBtn);
	document.removeEventListener('mousemove', dragDialog);
	document.removeEventListener('mouseup', stopDragDialog);
});
</script>

<style scoped>
.ai-assistant-btn {
	position: fixed;
	width: 60px;
	height: 60px;
	background: #4f46e5;
	color: white;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: move;
	user-select: none;
	box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
	z-index: 9999;
	transition: all 0.3s ease;
}

.ai-assistant-btn:hover {
	transform: scale(1.1);
	box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
}

.ai-assistant-btn:active {
	cursor: grabbing;
}

.ai-icon {
	font-size: 18px;
	font-weight: bold;
}

.dialog-header {
	padding: 15px;
	background: #4f46e5;
	color: white;
	display: flex;
	justify-content: space-between;
	align-items: center;
	cursor: move;
}

.dialog-header h3 {
	margin: 0;
	font-size: 18px;
}

.close-btn {
	background: none;
	border: none;
	color: white;
	font-size: 20px;
	cursor: pointer;
}

.dialog-content {
	flex: 1;
	padding: 15px;
	overflow-y: auto;
}

.message {
	margin-bottom: 12px;
	padding: 8px 12px;
	border-radius: 12px;
	max-width: 80%;
	word-break: break-word;
}

.message.user {
	background: #4f46e5;
	color: white;
	margin-left: auto;
}

.message.ai {
	background: #f0f0f0;
	margin-right: auto;
}

.typing-indicator {
	display: flex;
	gap: 4px;
	margin-bottom: 12px;
}

.typing-indicator span {
	width: 8px;
	height: 8px;
	background: #94a3b8;
	border-radius: 50%;
	display: inline-block;
	animation: typingAnimation 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
	animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
	animation-delay: 0.4s;
}

@keyframes typingAnimation {

	0%,
	60%,
	100% {
		transform: translateY(0);
	}

	30% {
		transform: translateY(-4px);
	}
}

.dialog-input {
	padding: 12px;
	border-top: 1px solid #eee;
	display: flex;
	gap: 8px;
}

.dialog-input input {
	flex: 1;
	padding: 8px 12px;
	border: 1px solid #ddd;
	border-radius: 20px;
	outline: none;
}

.dialog-input button {
	padding: 8px 16px;
	background: #4f46e5;
	color: white;
	border: none;
	border-radius: 20px;
	cursor: pointer;
}

.dialog-input button:hover {
	background: #4338ca;
}

@media (max-width: 480px) {
	.ai-dialog {
		width: 90%;
		height: 70vh;
		left: 5% !important;
		top: 15vh !important;
	}
}
</style>